package com.xhwl.centiotdata.suppliersystem.dahua;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.DeviceDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/14/ 09:00
 */
@Service
public class DeviceDaHuaHandler {
    private static final Logger log = LoggerFactory.getLogger(DeviceDaHuaHandler.class);

    @Autowired
    private GeneralDaHuaHandler generalDaHuaHandler;

    public List<DeviceDaHuaDTO> pullDevice(DeviceIntegrationConfigDTO configDTO) {
        HashMap<String, Object> param = new HashMap<>(1);
        if (Integer.valueOf(1).equals(configDTO.getDeviceType())) {
            param.put("unitType", 7);
        }
        HashMap<String, Object> jsonParam = new HashMap<>(1);
        jsonParam.put("param", param);
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("interfaceId", DaHuaConstant.ADMIN_001_006);
        params.put("jsonParam", JSON.toJSONString(jsonParam));

        JSONObject resultObject = generalDaHuaHandler.post(DaHuaConstant.ADMIN_REST_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null) {
            return null;
        }
        JSONObject resultJSONObject = resultObject.getJSONObject("result");
        if ("false".equals(resultJSONObject.getString("code"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaConstant.ADMIN_REST_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        if (StringUtils.isEmpty(dataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaConstant.ADMIN_REST_URL, JSON.toJSONString(params));
            return null;
        }
        List<DeviceDaHuaDTO> deviceDaHuaDTOList = JSONObject.parseArray(dataStr, DeviceDaHuaDTO.class);
        if (CollectionUtils.isEmpty(deviceDaHuaDTOList)) {
            return null;
        }
        return deviceDaHuaDTOList;
    }

}
